package com.elot.core.types;

import java.util.ArrayList;

public class DynamicArrayList<E> extends ArrayList<E> {
	
	private static final long serialVersionUID = 1L;
	
	private Class<E> instance;
	
	public DynamicArrayList(Class<E> instance) {
		this.instance = instance;
	}
	
	@Override
	public E get(int index) {
		
		while ( super.size() <= index) {
			try {
				super.add( instance.newInstance() );
			}catch (Exception e){
				super.add(null);
			}
		}
		
		return super.get(index);
	}
	
	@Override
	public E set(int index, E element)
	{
		int delta = index - size();
		while (delta > 0)
		{
			try {
				super.add(instance.newInstance());
			} catch (Exception e) {
				super.add(null);
			}
			delta--;
		}
		if (delta == 0)
			super.add(element);
		else
			return super.set(index, element);
		
		return null;
	}
	
}
